import axios from "axios";
var requestConfig = {
      serverUrl: "",
      token: ""
    };
var axiosIns;

/* application/json提交 */
const request = function (method, params, success, fail) {
  let config = requestConfig;
  if (!config.serverUrl) {
    throw new Error("请执行setConfig方法配置请求地址");
  }
  if (method) {
    let config = {headers: { "Content-Type": "application/json" }};
    let axiosObj = axiosIns.post(`/${method}`, `${JSON.stringify(params)}`, config);
    /* 执行success或者error方法 */
    axiosObj.then(response => {
      if (typeof success === "function") {
        success(response.data);
      }
    }).catch((error) => {
      if (typeof fail === "function") {
        fail(error);
      }
    })
    return axiosObj;
  } else {
    /* //处理错误 */
    throw new Error("请指定请求地址!");
  }
}

/**
 * 包含上传文件和普通请求的表单方式
 * @param {Object} params 请求具体参数
 */
const formRequest = function (method, params, successCallback, failCallback) {
  let formDataObj = new FormData();
  for (let o in params) {
    /* //针对，如果是文件上传的话，特殊处理 */
    if (o === "files") {
      params[o].forEach(item => {
        formDataObj.append(o, item)
      })
    } else {
      formDataObj.append(o, params[o])
    }
  }
  if (method) {
    let ajaxObj = axiosIns.post(`/${method}`, formDataObj, { headers: { "Content-Type": 'multipart/form-data' } });

    if (typeof successCallback === 'function') {
      ajaxObj.then(function (response) {
        if (typeof successCallback === 'function') {
          successCallback(response.data);
        }
      });
    }
    if (typeof failCallback === 'function') {
      ajaxObj.catch(failCallback);
    }
    return ajaxObj;
  } else {
    /* //处理错误 */
    throw new Error("请指定请求地址!");
  }
}

/* get提交 */
const requestGet = function (method, params, success, fail) {
  let config = requestConfig;
  if (!config.serverUrl) {
    throw new Error("请执行setConfig方法配置请求地址");
  }
  if (method) {
    let axiosObj = axiosIns.get(`/${method}`, `${JSON.stringify({params: params})}`);
    /* 执行success或者error方法 */
    axiosObj.then(response => {
      if (typeof success === "function") {
        success(response.data);
      }
    }).catch((error) => {
      if (typeof fail === "function") {
        fail(error);
      }
    })
    return axiosObj;
  } else {
    /* //处理错误 */
    throw new Error("请指定请求地址!");
  }
}

const setConfig = function (serverUrl, token) {
  /* //创建axios实例 */
  axiosIns = axios.create({
    baseURL: serverUrl
  });
  requestConfig.serverUrl = serverUrl;
}
export {setConfig, request, formRequest, requestGet};
